package com.cgycms.webloggather.util;

import com.alibaba.fastjson.JSON;
import com.cgycms.weblogcommon.model.gather.GatherConfig;
import com.cgycms.weblogcommon.model.gather.GatherInputs;
import com.cgycms.weblogcommon.model.gather.GatherMonitor;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @ClassName : GatherContext
 * @Description : 获取配置对象
 * @Author : Wlc
 * @Date: 2020-09-14 16:02
 */
@Component
public class GatherContext {

    private static Logger log = LoggerFactory.getLogger(GatherContext.class);

    @Autowired
    private GatherConfigPath configPath;

    private GatherMonitor monitor;

    public GatherMonitor findGatherMonitorConfig() {
        if (monitor != null) {
            return monitor;
        }
        Resource resource = null;
        String cgPath = configPath.getConfigPath();
        if (!StringUtils.isEmpty(cgPath)) {
            log.info("指定位置加载配置文件:" + cgPath);
            resource =  new FileSystemResource( new File(cgPath));
        } else {
            resource = new ClassPathResource("gather.json");
            log.info("默认位置加载配置文件...");
        }
        try {
            String inputJson = FileUtils.readFileToString(resource.getFile(), "UTF-8");
            monitor = JSON.parseObject(inputJson, GatherMonitor.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return monitor;
    }

    public GatherConfig getConfig() {
        return this.findGatherMonitorConfig().getGatherConfig();
    }

    public List<GatherInputs> getInputs() {
        return this.findGatherMonitorConfig().getInputs();
    }

}
